<script setup>
	const recordModule = uni.requireNativePlugin("Marcent-Audio")
	var g_wakelock = null; 
	let socketID;
	const location = uni.requireNativePlugin('Ba-Location');
	const floatWindow = uni.requireNativePlugin('Ba-FloatWindow')
	// import amapFile from '@/libs/amap-wx.js'
	import UpdateMonitor from '@/utils/update-monitor.js';
	import sceneInfo from '@/utils/scene-info.js';
	import { useThemeStore } from '@/store/index.js'
	
	const globalData = reactive({
		longitude: undefined,
		latitude: undefined,
		loginType: false
	})
	const amapPlugin = ref(null);
	const key = ref('bb6f4ed802756f963b37c184ce4e9766');
	const timer = ref(null);
	const timmer = ref(null);
	const msgList = ref([]);
	const minTimeMs = ref(30);
	const minDistanceM = ref(1);
	const ttsModule = ref(null);
	// 悬浮窗 **************start***********
	const widthRatio = ref(0.13);
	const heightRatio = ref(0.13);
	const xRatio = ref(0.8);
	const yRatio = ref(0.8);
	const moveType = ref(3);
	const slideLeftMargin = ref(0);
	const duration = ref(500);
	const slideRightMargin = ref(0);
	const desktopShow = ref(true);
	const tag = ref('');
	const iconPath = ref('ba_float_win_icon');
	// 悬浮窗 **************end***********
	const videoUrl = ref('');
	const time = ref(0);
	const timeTask = ref(null);
	const state = ref('初始化');
	
	onLaunch((options) => {
		// console.log(options);
		console.log('App Launch')
		ttsModule.value = uni.requireNativePlugin("hm-tts-TtsModule")
		ttsModule.value.init((ret) => {});
		initIcon()
		subLocation();
		
		// 初始化录音回调
		initRecordModule()
		// 初始化录音播放器
		initInnerAudio()
	})
	onShow((options) => {
		// console.log(options);
		console.log('App Show')
		// UpdateMonitor()
		// const scene = sceneInfo(options.scene);
		// console.log(scene);
		plus.device.setWakelock(true)
		globalData.loginType = uni.getStorageSync('token') ? true : false
		
		hideIcon()
		handleDrawOverlaysPermission()
	})
	onHide(() => {
		console.log('App Hide')
		ttsModule.value.speak({text: '汪伦代驾将继续为您服务~'})
		showIcon()
	})
	onExit(() => {
		stopL()
	})

	onPageNotFound(() => {
		uni.reLaunch({
			url: "/pages/index/index"
		});
	})
	onThemeChange((e) => {
		console.log("系统主题：", e);
		const themeStore = useThemeStore()
		themeStore.setTheme(e.theme)
	})
	
	const getLocationData = () => {
		timmer.value && clearInterval(timmer.value)
		timmer.value = setInterval(() => {
		  console.log(234234234)
		  uni.getLocation({
			type: 'GCJ-02',
			success: function (res) {
			  console.log('当前位置的经度：' + res.longitude);
			  console.log('当前位置的纬度：' + res.latitude);
			  globalData.latitude = res.latitude;
			  globalData.longitude = res.longitude;
			},
			fail (e) {
			  console.log(22334, e)
			}
		  })
		}, 4000)
	}
	// 获取定位3************开始**************************************
	const startL = () => {//开启定位
		location.start(res => {
			console.log(123123132, res)
			if (res.ok) {
				subLocation()
				subLocationStatus()
			}
			uni.showToast({
				title: '实时定位开启成功！',
				icon: "none",
				duration: 3000
			})
		}, { minTimeMs: minTimeMs.value, minDistanceM: minDistanceM.value });
	}
	const stopL = () => {//关闭定位
		location.stop(res => {
			console.log(res);
			uni.showToast({
				title: '您已退出，实时定位服务已关闭！',
				icon: "none",
				duration: 3000
			})
		})
	}
	const isLocationService = () => {//定位服务是否开启
		location.isLocationService(res => {
			console.log('是否開啓',res.data.isLocationService);
			if (!res.data.isLocationService) {
				startL()
			} else {
				subLocation()
				subLocationStatus()
			}
		});
	}
	const isLocationEnable = () => {//定位开关是否打开
		location.isLocationEnable(res => {
			if (!res.data.isLocationEnable) {
				uni.showToast({
					title: '手机定位信息未打开，请前往设置！',
					icon: "none",
					duration: 3000
				})
				goSetting()
			} else {
				isLocationService()
			}
		});
	}
	const goSetting = () => {//跳转到定位服务设置界面
		location.goSetting(res => {
			console.log(123123123, res);
			if (res.ok) {
				isLocationService()
			}
		})
	}
	const subLocation = () => {//订阅定位信息
		location.subLocation(res => {
			// console.log(111222333, res)
			if (res.data) {
				console.log(11111111111111, res.data.latitude, res.data.longitude);
				globalData.latitude = res.data.latitude;
				globalData.longitude = res.data.longitude;
			}
		});
	}
	const subLocationStatus = () => {//订阅定位状态变化
		location.subLocationStatus(res => {
			if (res.data) {
				console.log(112233445566, res.data.latitude, res.data.longitude);
				globalData.latitude = res.data.latitude;
				globalData.longitude = res.data.longitude;
			}
		});
	}
	const subGpsStatus = () => {//订阅 gps和 搜星变化
		location.subGpsStatus(res => {
			console.log(res);
			if (res.data) {
				msgList.value.unshift(JSON.stringify(res.data))
				msgList.value.unshift(dateUtil.now())
			}
			uni.showToast({
				title: res.msg,
				icon: "none",
				duration: 3000
			})
		});
	}
	// 获取定位3************结束**************************************
	// 悬浮窗 **************start***********
	const initIcon = () => {//初始化
		floatWindow.initIcon({
			widthRatio: widthRatio.value,
			heightRatio: heightRatio.value,
			xRatio: xRatio.value,
			yRatio: yRatio.value,
			moveType: moveType.value,
			slideLeftMargin: slideLeftMargin.value,
			slideRightMargin: slideRightMargin.value,
			duration: duration.value,
			desktopShow: desktopShow.value,
			tag: tag.value,
			iconPath: iconPath.value
		}, (res) => {
			uni.showToast({
				title: res.msg,
				icon: "none",
				duration: 3000
			})
		})
	}
	const showIcon = () => {//显示
		floatWindow.showIcon({ tag: tag.value }, (res) => {
			console.log(res);
			if(res.code && res.code==2){
				toLaunch();
			}
			// uni.showToast({
			// 	title: res.msg,
			// 	icon: "none",
			// 	duration: 3000
			// })
		})
	}
	const hideIcon = () => {//隐藏
		floatWindow.hideIcon({ tag: tag.value });
	}
	const changeIcon = () => {
		floatWindow.changeIcon({
			tag: tag.value,
			iconPath: iconPath.value
		}, (res) => {
			console.log(res);
			uni.showToast({
				title: res.msg,
				icon: "none",
				duration: 3000
			})
		})
	}
	const toLaunch = () => {//应用在后台时，可调起
		let platform = uni.getSystemInfoSync().platform;
		if (platform == 'android') {
			var main = plus.android.runtimeMainActivity();
			var Intent = plus.android.importClass("android.content.Intent");
			var intent = new Intent(Intent.ACTION_MAIN);
			intent.setClassName(main, "io.dcloud.PandoraEntry");
			intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			//intent.putExtra("xxx", "111111");//携带参数（如要在调起后，需要执行后续逻辑，可在这里自定义参数，在app.vue的onShow事件中监听，如下）
			main.startActivity(intent);
		}
	}
	const checkDrawOverlaysPermission = () => {// 检查悬浮窗权限
		var Context = plus.android.importClass("android.content.Context");
		var Settings = plus.android.importClass("android.provider.Settings");
		var main = plus.android.runtimeMainActivity();
		var canDrawOverlays = Settings.canDrawOverlays(main);
		return canDrawOverlays;
	}
	// 打开悬浮窗
	const handleDrawOverlaysPermission = () => {
		if (!checkDrawOverlaysPermission()) {
			uni.showModal({
				title: '提示',
				content: '需要开启【悬浮窗】和【后台弹窗】权限才能正常使用该功能！',
				confirmText: '去开启',
				success: function (res) {
					if (res.confirm) {
						openPermissionSettings();
					}
				}
			})
		}
	}
	// 打开台弹窗权限设置界面
	const openPermissionSettings = () => {
		var Intent = plus.android.importClass("android.content.Intent");
		var Settings = plus.android.importClass("android.provider.Settings");
		var main = plus.android.runtimeMainActivity();
		var intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		var uri = plus.android.importClass("android.net.Uri").fromParts("package", main.getPackageName(), null);
		intent.setData(uri);
		main.startActivity(intent);
	}
	// 悬浮窗 **************end***********
	
	// 允许程序后台运行，以持续获取GPS位置
	const wakeLock = () => {
		console.log(11223, '允许程序后台运行，以持续获取GPS位置')
		//Android  
		var main = plus.android.runtimeMainActivity();  
		var Context = plus.android.importClass("android.content.Context");  
		var PowerManager = plus.android.importClass("android.os.PowerManager");  
		var pm = main.getSystemService(Context.POWER_SERVICE);  
		g_wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ANY_NAME");  
		g_wakelock.acquire();  
	}
	// 结束程序后台运行
	const releaseWakeLock = () => {
		if(g_wakelock != null && g_wakelock.isHeld()) {
			g_wakelock.release();  
			g_wakelock = null;  
		} 
	}
	
	// 录音 start**********************************************
	// 初始化录音回调
	const initRecordModule = () => {
		// BLANK 注意这里on与Start之前的空格手动去掉下
		recordModule.onStart(e => {
			console.log('录音开始回调', e)
			if (e.code == 200) {
				console.log('开始录音');
				if (timeTask.value)
				clearInterval(timeTask.value)
				time.value = 0
				timeTask.value = setInterval(() => {
					time.value++
				}, 1000)
				state.value = '录音中'
			}
		})
		// BLANK 注意这里on与Pause之前的空格手动去掉下
		recordModule.onPause(e => {
			console.log('录音暂停回调', e);
			if (e.code == 0) {
				console.log('暂停成功');
				state.value = '暂停中'
			} else if (e.code == 1) {
				console.log('继续成功');
				state.value = '继续录音中'
			}
		})
		// BLANK 注意这里on与Stop之前的空格手动去掉下
		recordModule.onStop(e => {
			console.log('录音结束回调', e);
			if (e.code == 200) {
				videoUrl.value = '_doc/recordAacPlus/' + e.result + '.aac'
				console.log('录音结束,存储路径为', videoUrl.value);
				state.value = '录音结束'
				uploadFile()
				if (timeTask.value)
				clearInterval(timeTask.value)
			}
		})
	}
	// 初始化播放器
	const initInnerAudio = () => {
		innerAudioContext.value = uni.createInnerAudioContext()
		innerAudioContext.value.onPlay(e => {
			console.log('播放音频开始', e)
		})
		// BLANK 注意这里on与Stop之前的空格手动去掉下
		innerAudioContext.value.onStop(e => {
			console.log('播放音频停止', e)
		})
		// BLANK 注意这里on与Ended之前的空格手动去掉下
		innerAudioContext.value.onEnded(e => {
			console.log('播放音频自然播放结束', e)
		})
		innerAudioContext.value.onError(e => {
			console.log('播放音频错误', e)
		})
	}
	const startRecord = () => {
		recordModule.start({
			rootPath: plus.io.convertLocalFileSystemURL('_doc/recordAacPlus/')
		})
	}
	const stopRecord = () => {
		recordModule.stop()	
	}
	const playRecord = () => {
		innerAudioContext.value.stop()
		innerAudioContext.value.src = videoUrl.value
		innerAudioContext.value.play()
	}
	const uploadFile = () => {
		console.log(123123123, videoUrl.value)
		let filePath = videoUrl.value
		uni.uploadFile({
			url: `https://www.huaguduo.top/api/app/order/inluyin`,
			filePath,
			header: {
			  'AuthToken': uni.getStorageSync('token') || ''
			},
			name: 'file',
			success: (res) => {
				console.log('File uploaded:', res);
			},
			fail: (error) => {
				console.error('Error uploading file:', error);
			},
		});
	}
</script>

<style lang="scss">
	@import "@/uni_modules/uview-plus/index.scss";
	.contanter {
		// border: 1px solid red;
		width: 100%;
		font-size: 14px;
	}
	uni-page-body {
		font-size: 30rpx !important;
	}
	// 自定义头部，状态栏盒子样式
	.status_bar {
		height: var(--status-bar-height);
		width: 100%;
		background-color: #fff;
	}
	// tab切换选中加下边框
	.active-bb {
		&::after {
			content: '';
			position: absolute;
			width: 90%;
			height: 5rpx;
			background-color: $blue;
			left: 5%;
			bottom: -25rpx;
		}
	}
	// filed
	.u-field {
		padding: 26rpx 34rpx !important;
		.u-label-text {
			font-weight: 700 !important;
		}
	}
	// 提交按钮
	.u-btn--primary {
		background: $blue !important;
	}
	.u-size-default {
		width: 682rpx !important;
		height: 88rpx !important;
		font-weight: 700 !important;
	}
	// cell组件右边箭头对其文字
	.u-cell_title {
		font-weight: 700 !important;
		color: #333 !important;
	}
	.u-cell__right-icon-wrap {
		height: 55rpx !important;
	}
  @import 'sard-uniapp/index.scss';
  @import './common/common.scss'
</style>

<style></style>